package com.ev.hr.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSONObject;
import com.ev.apis.model.DsResultResponse;
import com.ev.custom.domain.*;
import com.ev.custom.service.ContentAssocService;
import com.ev.custom.service.DictionaryService;
import com.ev.framework.config.ConstantForDevice;
import com.ev.framework.config.ConstantForHr;
import com.ev.framework.il8n.MessageSourceHandler;
import com.ev.framework.utils.*;
import com.ev.hr.domain.*;
import com.ev.hr.service.*;
import com.ev.hr.vo.*;
import com.ev.system.domain.DeptDO;
import com.ev.system.service.DeptService;
import com.ev.system.service.RoleService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.ev.hr.dao.EmployeeInfoDao;
import com.google.common.collect.Maps;
import org.springframework.web.multipart.MultipartFile;


@Service
public class EmployeeInfoServiceImpl implements EmployeeInfoService {
	private static String RESUME_SOURCE = "1";

	@Autowired
	private ContentAssocService contentAssocService;
	@Autowired
	private EmployeeInfoDao employeeInfoDao;
	@Autowired
	private AfterExperienceService afterExperienceService;
	@Autowired
	private InterviewRecordService interviewRecordService;
	@Autowired
	private CandidateInfoService candidateInfoService;
	@Autowired
	private DeptService deptService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private PostInfoService postInfoService;
	@Autowired
	private RoleService roleService;


	@Autowired
	private MessageSourceHandler messageSourceHandler;
	
	@Override
	public EmployeeInfoDO get(Long id){
		return employeeInfoDao.get(id);
	}
	
	@Override
	public List<EmployeeInfoDO> list(Map<String, Object> map){
		return employeeInfoDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return employeeInfoDao.count(map);
	}
	
	@Override
	public int save(EmployeeInfoDO employeeInfo){
		return employeeInfoDao.save(employeeInfo);
	}
	
	@Override
	public int update(EmployeeInfoDO employeeInfo){
		return employeeInfoDao.update(employeeInfo);
	}

	@Override
	public int updateAll(EmployeeInfoDO employeeInfo){
		return employeeInfoDao.updateAll(employeeInfo);
	}
	
	@Override
	public int remove(Long id){
		return employeeInfoDao.remove(id);
	}
	
	@Override
	public int batchRemove(Long[] ids){
		return employeeInfoDao.batchRemove(ids);
	}

	@Override
	public R saveAndVerify(EmployeeInfoSaveParam saveParam){
		EmployeeInfoDO employeeInfoDO = saveParam.getEmployeeInfoDO();
		// 验证工号重复
		EmployeeInfoDO checkDo = new EmployeeInfoDO(employeeInfoDO.getId(),employeeInfoDO.getEmployeeCode(),null,null);
		if(this.checkRepeat(checkDo)){
			return R.error(messageSourceHandler.getMessage("hr.employee.duplicate",new String[]{"工号",employeeInfoDO.getEmployeeCode()}));
		}
		checkDo = new EmployeeInfoDO(employeeInfoDO.getId(),null,employeeInfoDO.getIdNumber(),null);
		if(this.checkRepeat(checkDo)){
			return R.error(messageSourceHandler.getMessage("hr.employee.duplicate",new String[]{"身份证号",employeeInfoDO.getIdNumber()}));
		}
		checkDo = new EmployeeInfoDO(employeeInfoDO.getId(),null,null,employeeInfoDO.getMobilePhone());
		if(this.checkRepeat(checkDo)){
			return R.error(messageSourceHandler.getMessage("hr.employee.duplicate",new String[]{"手机号码",employeeInfoDO.getMobilePhone()}));
		}
		/**
		 * 先保存主表信息
		 */
		if(employeeInfoDO.getId()!=null){
			/**
			 * check部门或者岗位有没有变更，如果变更，则生成转岗记录
			 */
			EmployeeInfoDO before = employeeInfoDao.get(employeeInfoDO.getId());
			if(!Objects.equals(before.getDeptId(),employeeInfoDO.getDeptId()) || !Objects.equals(before.getEmployeePost(),employeeInfoDO.getEmployeePost())){
				AfterExperienceDO afterExperienceDO = new AfterExperienceDO();
				afterExperienceDO.setEmployeeId(employeeInfoDO.getId());
				afterExperienceDO.setEmployeeCode(employeeInfoDO.getEmployeeCode());
				afterExperienceDO.setEmployeeName(employeeInfoDO.getEmployeeName());
				afterExperienceDO.setBeforeAdjustmentDept(before.getDeptId());
				afterExperienceDO.setBeforeAdjustmentPost(before.getEmployeePost());
				afterExperienceDO.setAfterAdjustmentDept(employeeInfoDO.getDeptId());
				afterExperienceDO.setAfterAdjustmentPost(employeeInfoDO.getEmployeePost());
				afterExperienceDO.setPostAdjustmentTime(new Date());
				afterExperienceService.save(afterExperienceDO);
			}
			employeeInfoDao.update(employeeInfoDO);

		}else{
			employeeInfoDao.save(employeeInfoDO);
		}
		/**
		 * 先删除附件
		 */
		contentAssocService.removeByAssocIdAndType(new Long[]{employeeInfoDO.getId()}, ConstantForHr.JOB_DESCRIPTION_CONTENT);
		/**
		 * 保存附件信息
		 */
		contentAssocService.saveListForEntity(employeeInfoDO.getId(),saveParam.getContentAssocList(), ConstantForHr.JOB_DESCRIPTION_CONTENT);

		if(StringUtils.isNoneEmpty(saveParam.getSource()) && RESUME_SOURCE.equals(saveParam.getSource())){
			ResumeStateVO resumeStateVO = new ResumeStateVO();
			resumeStateVO.setUpdateType(5);
			List<Long> list = Lists.newArrayList();
			String idNumber = saveParam.getEmployeeInfoDO().getIdNumber();
			Map<String,Object> map = Maps.newHashMap();
			map.put("idNumber",idNumber);
			List<CandidateInfoDO> candidate = candidateInfoService.list(map);
			if (candidate.size() > 0) {
				list.add(candidate.get(0).getId());
				resumeStateVO.setCandidateIds(list);
				interviewRecordService.updateResumeState(resumeStateVO);
			}
		}
		Map<String,Object>  result= new HashMap<>();
		result.put("id",employeeInfoDO.getId());
		return R.ok(result);
	}

	@Override
	public Map<String, Object> getById(Long id) {
		/**
		 * 获取主体信息
		 */
		Map<String,Object> employeeInfoDO = employeeInfoDao.getById(id);
		/**
		 * 获取附件数据
		 */
		List<ContentAssocDO> contentAssocList = contentAssocService.list(new HashMap<String,Object>(2){{put("assocId",id);put("assocType",ConstantForHr.JOB_DESCRIPTION_CONTENT);}});
		/**
		 * 结果组装
		 */
		EmployeeInfoDetail employeeInfoDetail = new EmployeeInfoDetail();
		employeeInfoDetail.setEmployeeInfoDO(employeeInfoDO);
		employeeInfoDetail.setContentAssocList(contentAssocList);
		if (employeeInfoDO != null) {
			Map<String,Object> result = Maps.newHashMap();
			result.put("data",employeeInfoDetail);
			return R.ok(result);
		}
		return R.error();
	}

	@Override
	public Map<String, Object> pageList(EmployeeInfoPageParam pageParam) {
		Integer isCreateUser = pageParam.getIsCreateUser();
		if (isCreateUser == null) {
			isCreateUser = 0;
		}
		pageParam.setIsCreateUser(isCreateUser);

		Map<String,Object> result = Maps.newHashMap();
		pageParam.setEmployeeName(StringUtils.sqlLike(pageParam.getEmployeeName()));

		JSONObject o = (JSONObject) JSONObject.toJSON(pageParam);
		o.putAll(roleService.getDataPermission(3));

		List<Map<String, Object>> data = employeeInfoDao.pageList(o);
		int total = employeeInfoDao.pageCount(o);
		result.put("data", new DsResultResponse(pageParam.getPageno(),pageParam.getPagesize(),total,data));
		return R.ok(result);
	}

	@Override
	public R importRecord(MultipartFile file) {
		if (file.isEmpty()) {
			return R.error(messageSourceHandler.getMessage("file.nonSelect", null));
		}
		ImportParams params = new ImportParams();
		params.setTitleRows(1);
		params.setHeadRows(1);
		String[] importFields = {"员工工号","员工姓名","部门编号","岗位编号","用工状态"};
		params.setImportFields(importFields);
		List<EmployeeImportVO> employeeImportVOList;
		try {
			employeeImportVOList  =  ExcelImportUtil.importExcel(file.getInputStream(), EmployeeImportVO.class, params);
			employeeImportVOList = employeeImportVOList
					.stream()
					.filter(e-> StringUtils.isNoneEmpty(e.getEmployeeCode()))
					.collect(Collectors.toList());
		}catch(Exception e) {
			return R.error(messageSourceHandler.getMessage("file.upload.error", null));
		}
		//数据重复判断（工号，身份证号，手机号）
		List<String> employeeCodeList = employeeImportVOList.stream().map(EmployeeImportVO::getEmployeeCode).collect(Collectors.toList());
		List<String> employeeIdNumberList = employeeImportVOList.stream().map(EmployeeImportVO::getIdNumber).collect(Collectors.toList());
		List<String> employeeMobileList = employeeImportVOList.stream().map(EmployeeImportVO::getMobilePhone).collect(Collectors.toList());
		List<String> allCodeList = employeeInfoDao.getAllCodeList();
		List<String> allIdNumberList = employeeInfoDao.getAllIdNumberList();
		List<String> allMobileList = employeeInfoDao.getAllMobileList();
		employeeCodeList.addAll(allCodeList);
		employeeIdNumberList.addAll(allIdNumberList);
		employeeMobileList.addAll(allMobileList);
		List<String> duplicateElements = ListUtils.getDuplicateElements(employeeCodeList);
		if (duplicateElements.size() > 0) {
			String[] arg = {"员工编号", StringUtils.join(duplicateElements.toArray(), ",")};
			return R.error(messageSourceHandler.getMessage("basicInfo.isPresence", arg));
		}
		duplicateElements = ListUtils.getDuplicateElements(employeeIdNumberList);
		if (duplicateElements.size() > 0) {
			String[] arg = {"身份证号", StringUtils.join(duplicateElements.toArray(), ",")};
			return R.error(messageSourceHandler.getMessage("basicInfo.isPresence", arg));
		}
		duplicateElements = ListUtils.getDuplicateElements(employeeMobileList);
		if (duplicateElements.size() > 0) {
			String[] arg = {"手机号码", StringUtils.join(duplicateElements.toArray(), ",")};
			return R.error(messageSourceHandler.getMessage("basicInfo.isPresence", arg));
		}

		List<DeptDO> deptDOs = deptService.list(null);
		List<PostInfoDO> postInfoDOS = postInfoService.list(null);
		List<DictionaryDO> employeeStatusDOS = dictionaryService.listByType(ConstantForHr.DIC_TYPE_EMPLOYEE_STATUS);
		List<DictionaryDO> employeeTypeDOS = dictionaryService.listByType(ConstantForHr.DIC_TYPE_EMPLOYEE_TYPE);
		List<DictionaryDO> regTypeDOS = dictionaryService.listByType(ConstantForHr.DIC_TYPE_REG_TYPE);
		List<DictionaryDO> eduTypeDOS = dictionaryService.listByType(ConstantForHr.DIC_TYPE_EDU_BACK);
		List<DictionaryDO> polOutLookDOS = dictionaryService.listByType(ConstantForHr.DIC_TYPE_POL_OUTLOOK);

		List<EmployeeInfoDO> employeeInfoDOList = new ArrayList<>();
		if(employeeImportVOList.size()>0){
			for(EmployeeImportVO employeeImportVO : employeeImportVOList){
				EmployeeInfoDO employeeInfoDO = new EmployeeInfoDO();
				BeanUtils.copyProperties(employeeImportVO,employeeInfoDO);
				//下拉框数据赋值
				//部门
				for (DeptDO deptDO : deptDOs) {
					if (Objects.equals(deptDO.getDeptCode(),employeeImportVO.getDeptCode())) {
						employeeInfoDO.setDeptId(deptDO.getDeptId());
						break;
					}
				}
				//岗位
				for (PostInfoDO postInfoDO : postInfoDOS) {
					if (Objects.equals(postInfoDO.getPostCode(),employeeImportVO.getPostCode())) {
						employeeInfoDO.setEmployeePost(postInfoDO.getId());
						break;
					}
				}
				//用工状态
				for (DictionaryDO dictionaryDO : employeeStatusDOS) {
					if (Objects.equals(dictionaryDO.getName(),employeeImportVO.getEmploymentState())) {
						employeeInfoDO.setEmploymentState(dictionaryDO.getId());
						break;
					}
				}
				//用工类型
				for (DictionaryDO dictionaryDO : employeeTypeDOS) {
					if (Objects.equals(dictionaryDO.getName(),employeeImportVO.getEmploymentType())) {
						employeeInfoDO.setEmploymentType(dictionaryDO.getId());
						break;
					}
				}
				//户口类型
				for (DictionaryDO dictionaryDO : regTypeDOS) {
					if (Objects.equals(dictionaryDO.getName(),employeeImportVO.getRegisteredType())) {
						employeeInfoDO.setRegisteredType(dictionaryDO.getId());
						break;
					}
				}
				//最高学历
				for (DictionaryDO dictionaryDO : eduTypeDOS) {
					if (Objects.equals(dictionaryDO.getName(),employeeImportVO.getHighestEducation())) {
						employeeInfoDO.setHighestEducation(dictionaryDO.getId());
						break;
					}
				}
				//政治面貌
				for (DictionaryDO dictionaryDO : polOutLookDOS) {
					if (Objects.equals(dictionaryDO.getName(),employeeImportVO.getPoliticalOutlook())) {
						employeeInfoDO.setPoliticalOutlook(dictionaryDO.getId());
						break;
					}
				}
				//性别
				if ("男".equals(employeeImportVO.getEmployeeGender())) {
					employeeInfoDO.setEmployeeGender(1);
				} else {
					employeeInfoDO.setEmployeeGender(0);
				}
				//婚姻状况
				if ("已婚".equals(employeeImportVO.getMaritalStatus())) {
					employeeInfoDO.setMaritalStatus(1);
				} else {
					employeeInfoDO.setEmployeeGender(0);
				}
				// 使用状态(1是0否)
				employeeInfoDO.setDelFlag(0);
				employeeInfoDO.setCreateBy(ShiroUtils.getUserId());
				employeeInfoDO.setCreateTime(new Date());
				employeeInfoDOList.add(employeeInfoDO);
			}
			employeeInfoDao.batchSave(employeeInfoDOList);
		}
		return R.ok();
	}

	@Override
	public List<EmployeeInfoDO> listAll() {
		return employeeInfoDao.listAll();
	}

	@Override
	public int batchUpdate(List<EmployeeInfoDO> employeeInfo) {
		return employeeInfoDao.batchUpdate(employeeInfo);
	}

	@Override
	public int batchSave(List<EmployeeInfoDO> employeeInfo) {
		return employeeInfoDao.batchSave(employeeInfo);
	}

	private boolean checkRepeat(EmployeeInfoDO employeeInfoDO) {
		return employeeInfoDao.checkRepeat(employeeInfoDO)>0;
	}
}
